import os
from PIL import Image


def stack_images_in_directory(directory_path, output_path, spacing=10):
    """
    将目录中的所有图片水平堆叠在一起

    Args:
        directory_path: 包含图片的目录路径
        output_path: 堆叠后图片的保存路径
        spacing: 图片之间的间距（像素）
    """
    # 获取目录中所有图片文件
    image_files = [f for f in os.listdir(directory_path)
                   if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]

    # 按文件名排序（确保顺序正确）
    image_files.sort()

    if not image_files:
        print("目录中没有找到图片文件")
        return

    # 加载第一张图片以获取尺寸
    first_image = Image.open(os.path.join(directory_path, image_files[0]))
    height = first_image.height
    width = first_image.width

    # 计算总宽度
    total_width = width * len(image_files) + spacing * (len(image_files) - 1)

    # 创建一个新的空白画布
    stacked_image = Image.new('RGB', (total_width, height), (255, 255, 255))

    # 将图片堆叠到画布上
    x_offset = 0
    for img_file in image_files:
        img_path = os.path.join(directory_path, img_file)
        img = Image.open(img_path)

        # 确保所有图片大小一致
        if img.size != (width, height):
            img = img.resize((width, height))

        # 将图片粘贴到堆叠画布上
        stacked_image.paste(img, (x_offset, 0))

        # 更新偏移量
        x_offset += width + spacing

    # 保存堆叠后的图片
    stacked_image.save(output_path)
    print(f"堆叠后的图片已保存到: {output_path}")


# 使用示例
if __name__ == "__main__":
    input_directory = r"C:\Users\22775\Desktop\骨骼序列"
    output_file = os.path.join(input_directory, "stacked_sequence.png")

    stack_images_in_directory(input_directory, output_file)